#include "UdpServer.hpp"
#include "Comm.hpp"
#include <memory>
#include <vector>
#include <cstdio>

void Usage(std::string proc)
{
    std::cout << "Usage : \n\t" << proc << " local_port\n" << std::endl;
}

//黑指令名单
std::vector<std::string> black_words = {
    "rm",
    "unlink",
    "cp",
    "mv",
    "chmod",
    "exit",
    "reboot",
    "halt",
    "shutdown",
    "top",
    "kill",
    "dd",
    "vim",
    "vi",
    "nano",
    "man"
};

std::string OnMessageDefault(std::string request)
{
    return request + "[This is Default Message!]";
}

bool SafeCheck(std::string command)
{
    for(auto &k : black_words)
    {
        std::size_t pos = command.find(k);
        if(pos != std::string::npos) return false;
    }

    return true;
}

// ls -a -l/ rm / tocuh 
std::string ExecuteCommand(std::string command)
{
    if(!SafeCheck(command)) return "bad man!!";

    std::cout << "get a message: " << command << std::endl;
    FILE *fp = popen(command.c_str(), "r");
    if(fp == nullptr)
    {
        return "execute error, reason is unknown";
    }

    std::string response;
    char buffer[1024];
    while(true)
    {
        char *s = fgets(buffer, sizeof(buffer), fp);
        if(!s) break;
        else response += buffer;
    }
    pclose(fp);
    return response.empty() ? "success" : response;
}

// ./udp_server 8888
//一般测试端口为8888
//参数 ： 127.0.0.1 8888
int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        return Usage_Err;
    }

    // std::string ip = argv[1];
    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<UdpServer> usvr = std::make_unique<UdpServer>(ExecuteCommand, port);
    usvr->Init();
    usvr->Start();

    return 0;
}